<template>
  <div>
    <!-- 导航 -->
    <van-nav-bar title="登录" class="page-nav-bar" />
    <!-- 登录 -->
    <van-form @submit="onSubmit" ref="loginFrom">
      <van-field
        clearable
        v-model="user.mobile"
        name="mobile"
        placeholder="请输入手机号"
        :rules="userFormRules.mobile"
      >
        <!-- autocomplete="off"  输入记录提示 -->
        <i slot="left-icon" class="toutiao toutiao-shouji"></i
      ></van-field>
      <van-field
        clearable
        v-model="user.code"
        name="code"
        placeholder="验证码"
        :rules="userFormRules.code"
      >
        <i slot="left-icon" class="toutiao toutiao-yanzhengma"></i>

        <template #button>
          <van-count-down
            v-if="isCountDownShow"
            :time="60000"
            :auto-start="isCountDownShow"
            format="ss s"
            @finish="isCountDownShow = false"
          />
          <van-button v-else native-type="button" size="mini" type="primary" @click="onSendSms"
            >发送验证码</van-button
          >
        </template></van-field
      >
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { login, getSmsCode } from '@/api/user.js'
export default {
  name: 'loginPage',
  data() {
    return {
      isCountDownShow: false,
      user: {
        mobile: '',
        code: '',
      },
      userFormRules: {
        mobile: [
          { required: true, message: '手机号不能为空' },
          { pattern: /^1\d{10}$/, message: '输入的手机号格式不正确' },
        ],
        code: [
          { required: true, message: '验证码不能为空' },
          { pattern: /^\d{6}$/, message: '输入的验证码格式不正确' },
        ],
      },
    }
  },
  methods: {
    // 点击发送验证码
    async onSendSms() {
      try {
        await this.$refs.loginFrom.validate('mobile')
        console.log('验证成功')
        this.isCountDownShow = true
      } catch (error) {
        return console.log('表单验证失败', error)
      }
      //  发送验证码 网络请求
      try {
        let res = await getSmsCode(this.user.mobile)
        this.$toast.success('短信验证成功')
      } catch (error) {
        this.isCountDownShow = false
        if (error.response.status === 429) {
          this.$toast.fail('手机号验证频繁')
        } else {
          this.$toast.fail('手机号验证失败 请稍后重试')
        }
      }
    },
    async onSubmit() {
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true, //禁用背景点击
      })
      try {
        const res = await login(this.user)
 
        this.$toast.success('登录成功')
        this.$store.commit('setToken', res.data.data)
        this.$router.push('/layout/my')
        // console.log(res.data.data)
      } catch (error) {
        console.log(error, '错误')
        this.$toast.fail('登录失败')
      }
    },
  },
}
</script>

<style scoped lang="less"></style>
